<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { ExampleGenerate } from './detail'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/fukaact'
import detailStore from '@/store/modules/NewCacheData'
import { GetOptionData } from '@/api/modules/voucher.ts'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<ExampleGenerate>({
  startTime: '',
  endTime: '',
  flag: 0,
  fukaChange: 20,
  bgPic: '',
  nofukaPic: '',
  sharePic: '',
  shareTxt: '',
  shareZhuliTxt: '',
  shareSongTxt: '',
  zhuliBgpic: '',
  rulePic: '',
  lingfukaBgpic: '',
  drawBgpic: '',
  drawBtn: '',
  shareBtnpic: '',
  openIdMaxcount: '',
  fudaiUrl: '',
  myPrizeBg: '',
  descriptionTxt: '',
  descriptionPic: '',
  qvcodePic: '',
  drawStartTime: '',
  ruleBtn: '',
  myprizeBtn: '',
  cardList: [],
  zhuLiTicketList: [],
})

const id = route.query.id as string

const rules = reactive({
  aaaa: [
    { required: true, message: '请输入分享语', trigger: 'blur' },
  ],
})

const OptionList = reactive({
  CouponOption: [],
})

// 图片上传赋值
function handleUploadSuccess(url: string, key: string, keys?: string, index?: number) {
  if (index !== undefined) {
    // eslint-disable-next-line ts/ban-ts-comment
    // @ts-expect-error
    ruleForm.value[key][index][keys] = url
  }
  else {
    // eslint-disable-next-line ts/ban-ts-comment
  // @ts-expect-error
    ruleForm.value[key] = url
  }
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = { ...ruleForm.value }
      // console.log(params)
      if (Number(params.fukaChange) < 0 || Number(params.fukaChange) === 0) {
        ElMessage.error('福卡概率不能小于等于0，请检查福卡概率')
        return
      }
      else if (Number(params.fukaChange) > 100) {
        ElMessage.error('福卡概率不能大于100，请检查福卡概率')
        return
      }

      if (params.cardList.some((item) => {
        // if (Number(item.fukaChange) === 0) {
        //   return true
        // }
        if (Number(item.fukaChange) > 100) {
          return true
        }
        return false
      })) {
        ElMessage.error('福卡概率需要小于100，请检查福卡信息')
        return
      }

      // 计算填写了概率的 cardList 对象数量
      const nonZeroCount = params.cardList.filter(item => Number(item.fukaChange) > 0).length

      // 验证 cardList 中的 fukaChange 字段
      if (nonZeroCount < 1 || nonZeroCount > 2) {
        ElMessage.error('福卡概率只能填写一个或两个，请检查填写信息。')
        return
      }

      if (id) {
        // 编辑
        params.fukaActId = id
        // 将助力发券中的活动id填入
        params.zhuLiTicketList = params.zhuLiTicketList.map((item: any) => {
          if (item.fukaActId !== params.fukaActId) {
            item.fukaActId = params.fukaActId
          }
          return item
        })
        // console.log(params)

        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'fukaactIndex' })
          }
          else {
            ElMessage.error(`编辑失败。${res.errors}`)
          }
        })
      }
      else {
        // 添加
        // console.log(params)

        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('fukaFrom')
            router.push({ name: 'fukaactIndex' })
          }
          else {
            ElMessage.error(`添加失败。${res.errors}`)
          }
        })
      }
    }
    else {
      ElMessage.error('请检查表单')
    }
  })
}

function AddCard() {
  if (ruleForm.value.zhuLiTicketList) {
    ruleForm.value.zhuLiTicketList.push({
      ticketId: 0,
      usedUrl: '',
      change: 0,
      stock: 0,
      used: 0,
      flag: 0,
      picUrl: '',
      prizeListBg: '',
      prizeCoverpic: '',
    })
  }
  else {
    ruleForm.value.zhuLiTicketList = [
      {
        ticketId: 0,
        usedUrl: '',
        change: 0,
        stock: 0,
        used: 0,
        flag: 0,
        picUrl: '',
        prizeListBg: '',
        prizeCoverpic: '',
      },
    ]
  }
}

function DeleteItem(index: number) {
  ruleForm.value.zhuLiTicketList.splice(index, 1)
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('fukaFrom')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('fukaFrom', newValue)
    }
  }, { deep: true })

  // 获取所有商品
  const CouponOption: any = await GetOptionData()
  if (CouponOption.succeeded) {
    OptionList.CouponOption = CouponOption.data
    nextTick(() => {
      OptionList.CouponOption = CouponOption.data
    })
  }
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="活动状态">
              <el-switch
                v-model="ruleForm.flag"
                :active-value="1"
                :inactive-value="0"
                active-text="正常"
                inactive-text="关闭"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="开始时间">
              <el-date-picker
                v-model="ruleForm.startTime"
                type="datetime"
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="结束时间">
              <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="抽奖开始时间">
              <el-date-picker
                v-model="ruleForm.drawStartTime"
                type="datetime"
                placeholder="请选择时间"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="抽中卡概率">
              <el-input v-model="ruleForm.fukaChange" placeholder="请输入抽中卡概率" type="number">
                <template #append>
                  %
                </template>
              </el-input>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="每人最大发券量（-1为停止发券，0为不限制）">
              <el-input v-model="ruleForm.openIdMaxcount" placeholder="请输入每人最大发券量" type="number" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="福袋跳转地址">
              <el-input v-model="ruleForm.fudaiUrl" placeholder="请输入福袋跳转地址" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="活动分享语" prop="shareTxt">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入活动分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="助力分享语" prop="shareZhuliTxt">
              <el-input v-model="ruleForm.shareZhuliTxt" placeholder="请输入助力分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="送福卡分享语" prop="shareSongTxt">
              <el-input v-model="ruleForm.shareSongTxt" placeholder="请输入送福卡分享语" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="12">
            <ElFormItem label="试用说明文案" prop="descriptionTxt">
              <el-input v-model="ruleForm.descriptionTxt" placeholder="请输入试用说明文案" type="textarea" style="max-width: 550px;" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="上传图片">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="背景图" prop="bgPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.bgPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'bgPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="未抽福图" prop="nofukaPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.nofukaPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'nofukaPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图" prop="sharePic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.sharePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'sharePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="助力背景图" prop="zhuliBgpic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.zhuliBgpic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'zhuliBgpic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="规则图" prop="rulePic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.rulePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'rulePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="领福卡背景图" prop="lingfukaBgpic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.lingfukaBgpic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'lingfukaBgpic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="抽奖转盘图" prop="drawBgpic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.drawBgpic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'drawBgpic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="转盘指针图" prop="drawBtn">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.drawBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'drawBtn')"
              />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="分享按钮图" prop="shareBtnpic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.shareBtnpic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'shareBtnpic')"
              />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="我的奖品背景图" prop="myPrizeBg">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.myPrizeBg" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'myPrizeBg')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="试用说明图片" prop="descriptionPic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.descriptionPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'descriptionPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="企微二维码" prop="qvcodePic">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.qvcodePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'qvcodePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="false" :md="8">
            <ElFormItem label="规则按钮图" prop="ruleBtn">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.ruleBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'ruleBtn')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="false" :md="8">
            <ElFormItem label="我的奖品按钮图" prop="myprizeBtn">
              <ImageUpload
                width="auto" height="150" :size="5" :url="ruleForm.myprizeBtn" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'myprizeBtn')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="福卡信息">
        <ElRow :gutter="20">
          <ElCol v-for="(item, index) in ruleForm.cardList" :key="index" :md="8" class="mb-5">
            <el-card shadow="hover">
              <template #header>
                福卡{{ index + 1 }}
              </template>
              <el-scrollbar height="440px" :noresize="true">
                <div class="card-box">
                  <ElFormItem label="福卡名称">
                    <el-input v-model="item.fukaName" placeholder="请输入福卡名称" />
                  </ElFormItem>
                  <ElFormItem label="福卡概率">
                    <el-input v-model="item.fukaChange" placeholder="请输入福卡概率" type="number">
                      <template #append>
                        %
                      </template>
                    </el-input>
                  </ElFormItem>
                  <ElFormItem label="福卡未有图" style="grid-column: 1 / 3;">
                    <ImageUpload
                      height="150" width="auto" :size="1" :url="item.fukaPic1" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'cardList', 'fukaPic1', index)"
                    />
                  </ElFormItem>
                  <ElFormItem label="福卡已有图" style="grid-column: 1 / 3;">
                    <ImageUpload
                      height="150" width="auto" :size="1" :url="item.fukaPic2" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'cardList', 'fukaPic2', index)"
                    />
                  </ElFormItem>
                  <ElFormItem label="福卡翻中图" style="grid-column: 1 / 3;">
                    <ImageUpload
                      height="150" width="auto" :size="1" :url="item.fukaPic3" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'cardList', 'fukaPic3', index)"
                    />
                  </ElFormItem>
                </div>
              </el-scrollbar>
              <!-- <template #footer>
                <div class="flex justify-between">
                  <el-button type="success" @click="AddItem">
                    新增
                  </el-button>
                  <el-button type="danger" :disabled="ruleForm.cardList.length === 1" @click="DeleteItem(index)">
                    删除
                  </el-button>
                </div>
              </template> -->
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="助力发券">
        <el-button v-if="ruleForm.zhuLiTicketList?.length === 0" type="primary" @click="AddCard">
          添加
        </el-button>
        <ElRow :gutter="20">
          <ElCol v-for="(item, index) in ruleForm.zhuLiTicketList" :key="index" :md="8" class="mb-5">
            <el-card shadow="hover">
              <!-- <template #header>
                福卡{{ index + 1 }}
              </template> -->
              <el-scrollbar height="400px" :noresize="true">
                <div class="card-box">
                  <ElFormItem label="绑定券" style="grid-column: 1 / 3;">
                    <el-select v-model="item.ticketId" filterable placeholder="请选择券">
                      <el-option v-for="items in (OptionList.CouponOption as any[])" :key="items.id" :label="`${items.id}-${items.name}`" :value="items.id" />
                    </el-select>
                  </ElFormItem>
                  <ElFormItem label="跳转地址" style="grid-column: 1 / 3;">
                    <el-input v-model="item.usedUrl" placeholder="请输入跳转地址" />
                  </ElFormItem>
                  <ElFormItem label="状态">
                    <el-switch
                      v-model="item.flag"
                      :active-value="1"
                      :inactive-value="2"
                      active-text="可用"
                      inactive-text="停用"
                    />
                  </ElFormItem>
                  <ElFormItem label="概率">
                    <el-input v-model="item.change" placeholder="请输入概率" type="number">
                      <template #append>
                        %
                      </template>
                    </el-input>
                  </ElFormItem>
                  <ElFormItem label="库存">
                    <el-input v-model="item.stock" placeholder="请输入库存" type="number" />
                  </ElFormItem>
                  <ElFormItem label="已消耗">
                    <el-input v-model="item.used" placeholder="请输入已消耗" type="number" />
                  </ElFormItem>
                  <ElFormItem label="券弹窗图" style="grid-column: 1 / 3;">
                    <!-- <el-input v-model="item.picUrl" placeholder="请输入已消耗" type="number" /> -->
                    <ImageUpload
                      width="auto" height="150" :size="5" :url="ruleForm.zhuLiTicketList[index].picUrl" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'zhuLiTicketList', 'picUrl', index)"
                    />
                  </ElFormItem>
                  <ElFormItem label="卡券背景图" style="grid-column: 1 / 3;">
                    <!-- <el-input v-model="item.picUrl" placeholder="请输入已消耗" type="number" /> -->
                    <ImageUpload
                      width="auto" height="150" :size="5" :url="ruleForm.zhuLiTicketList[index].prizeListBg" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'zhuLiTicketList', 'prizeListBg', index)"
                    />
                  </ElFormItem>
                  <ElFormItem label="奖品封面" style="grid-column: 1 / 3;">
                    <!-- <el-input v-model="item.picUrl" placeholder="请输入已消耗" type="number" /> -->
                    <ImageUpload
                      width="auto" height="150" :size="5" :url="ruleForm.zhuLiTicketList[index].prizeCoverpic" :ext="['jpg', 'png']"
                      @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'zhuLiTicketList', 'prizeCoverpic', index)"
                    />
                  </ElFormItem>
                </div>
              </el-scrollbar>
              <template #footer>
                <div class="flex justify-between">
                  <el-button type="success" @click="AddCard">
                    新增
                  </el-button>
                  <el-button type="danger" :disabled="ruleForm.cardList.length === 1" @click="DeleteItem(index)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-card>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
